import * as echarts from 'echarts';
import ecStat from 'echarts-stat';
import { formatData, download } from '@/utils/index';
import eChartsOptionTemplate from '../../constant/echart.options.js';
import EventEmitter from 'eventemitter3';
import { EDITOR_STATE } from '../../constant/editor.state.js';

class EchartsController extends EventEmitter {
	constructor() {
		super();

		this.echartsInstance = null;
		this.eChartsOption = JSON.parse(JSON.stringify(eChartsOptionTemplate));
		this.mode = EDITOR_STATE.PREVIEW;
		this.originalData = null; // 保存原始数据

		// 画线功能相关状态
		this.lineDrawingState = {
			isDrawing: false,
			startPoint: null,
			tempLine: null,
			lines: [] // 存储所有已完成的线段
		};
	}

	init(options) {
		echarts.registerTransform(ecStat.transform.clustering);

		this.echartsInstance = echarts.init(options.dom, null, {
			renderer: 'canvas',
			useDirtyRect: false
		});

		// 确保图形元素数组存在
		if (!this.eChartsOption.graphic) {
			this.eChartsOption.graphic = [];
		}

		this.echartsInstance.setOption(this.eChartsOption);
		window.addEventListener('resize', this.echartsInstance.resize);
	}

	biggerPoint({ x, y, roomName }) {
		// 更新散点图数据，为每个点添加 symbolSize 属性
		this.eChartsOption.series[1].data = this.eChartsOption.series[1].data.map(item => {
			const [_x, _y] = item.value;

			if (_x === x && _y === y) {
				// 匹配的点变大2倍，使用橙色绿色配色
				return {
					...item,
					symbolSize: 36, // 原始大小18 * 2 = 36
					itemStyle: {
						color: '#FF6B35', // 深橙色，突出显示
						borderColor: '#FF6B35',
						borderWidth: 3
					}
				};
			} else {
				// 其他点保持原始大小和颜色
				return {
					...item,
					symbolSize: 18,
					itemStyle: {
						color: '#4CAF50', // 主绿色
						borderColor: '#FF6B35',
						borderWidth: 2
					}
				};
			}
		});

		this.echartsInstance.setOption(this.eChartsOption);
	}

	updateEchartsData(data) {
		// 如果是第一次调用，保存原始数据
		if (!this.originalData) {
			this.originalData = data;
		}

		const { lineData, pointData, roomLabelData } = formatData(data);

		// 保存当前的图形元素、新增点位和画线数据
		const currentGraphics = this.eChartsOption.graphic || [];
		const currentDrawnPoints = this.eChartsOption.series[3] || null;
		const currentDrawnLines = this.eChartsOption.series[4] || null;
		const currentDrawnLinePoints = this.eChartsOption.series[5] || null;
		const currentTempLines = this.eChartsOption.series[6] || null;
		const currentRectangles = this.eChartsOption.series[7] || null;
		const currentRectangleVertices = this.eChartsOption.series[8] || null;
		const currentTempRectangles = this.eChartsOption.series[9] || null;
		const currentRectangleFills = this.eChartsOption.series[10] || null;
		const currentTempRectangleVertices = this.eChartsOption.series[11] || null;

		this.eChartsOption.series[0] = lineData;
		this.eChartsOption.series[1] = pointData;
		this.eChartsOption.series[2] = roomLabelData;

		// 恢复图形元素、新增点位系列和画线系列
		this.eChartsOption.graphic = currentGraphics;
		if (currentDrawnPoints) {
			this.eChartsOption.series[3] = currentDrawnPoints;
		}
		if (currentDrawnLines) {
			this.eChartsOption.series[4] = currentDrawnLines;
		}
		if (currentDrawnLinePoints) {
			this.eChartsOption.series[5] = currentDrawnLinePoints;
		}
		if (currentTempLines) {
			this.eChartsOption.series[6] = currentTempLines;
		}
		if (currentRectangles) {
			this.eChartsOption.series[7] = currentRectangles;
		}
		if (currentRectangleVertices) {
			this.eChartsOption.series[8] = currentRectangleVertices;
		}
		if (currentTempRectangles) {
			this.eChartsOption.series[9] = currentTempRectangles;
		}
		if (currentRectangleFills) {
			this.eChartsOption.series[10] = currentRectangleFills;
		}
		if (currentTempRectangleVertices) {
			this.eChartsOption.series[11] = currentTempRectangleVertices;
		}

		// 使用 replaceMerge 选项确保系列正确更新
		this.echartsInstance.setOption(this.eChartsOption);
	};

	// 更新图形元素位置（当缩放时调用）
	updateGraphicPositions() {
		// 强制重新渲染图表，确保新增点位正确显示
		this.echartsInstance.setOption(this.eChartsOption);
	}

	// 获取当前新增点位数量
	getGraphicCount() {
		return this.eChartsOption.series[3] ? this.eChartsOption.series[3].data.length : 0;
	}

	// 清理临时线段
	_clearTempLine() {
		if (this.eChartsOption.series[6]) {
			this.eChartsOption.series[6].data = [];
		}

		this.echartsInstance.setOption(this.eChartsOption);
		this.lineDrawingState.isDrawing = false;
		this.lineDrawingState.startPoint = null;
	}

	// 重置为显示所有数据
	resetToOriginalData() {
		if (this.originalData) {
			this.updateEchartsData(this.originalData);
		}
	};

	captureChart() {
		this.echartsInstance.resize();

		const dataURL = this.echartsInstance.getDataURL({
			type: 'png',
			pixelRatio: 2,      // 提高截图清晰度
			backgroundColor: '#fff',
			excludeComponents: ['toolbox', 'dataZoom'],
			useViewBox: true
		});

		download(dataURL, 'chart-snapshot.png');
	};

	clearCanvas() {
		this.echartsInstance.clear();
		this.eChartsOption = JSON.parse(JSON.stringify(eChartsOptionTemplate));
		// 确保图形元素也被清空
		this.eChartsOption.graphic = [];
		// 确保新增点位系列也被清空
		if (this.eChartsOption.series[3]) {
			this.eChartsOption.series[3].data = [];
		}
		// 确保画线系列也被清空
		if (this.eChartsOption.series[4]) {
			this.eChartsOption.series[4].data = [];
		}
		// 确保画线点位系列也被清空
		if (this.eChartsOption.series[5]) {
			this.eChartsOption.series[5].data = [];
		}
		// 确保临时线段系列也被清空
		if (this.eChartsOption.series[6]) {
			this.eChartsOption.series[6].data = [];
		}
		// 确保矩形系列也被清空
		if (this.eChartsOption.series[7]) {
			this.eChartsOption.series[7].data = [];
		}
		// 确保矩形顶点系列也被清空
		if (this.eChartsOption.series[8]) {
			this.eChartsOption.series[8].data = [];
		}
		// 确保临时矩形系列也被清空
		if (this.eChartsOption.series[9]) {
			this.eChartsOption.series[9].data = [];
		}
		// 确保矩形填充系列也被清空
		if (this.eChartsOption.series[10]) {
			this.eChartsOption.series[10].data = [];
		}
		// 确保临时矩形顶点系列也被清空
		if (this.eChartsOption.series[11]) {
			this.eChartsOption.series[11].data = [];
		}
		// 重置画线状态
		this.lineDrawingState = {
			isDrawing: false,
			startPoint: null,
			tempLine: null,
			lines: []
		};
		this.echartsInstance.setOption(this.eChartsOption);
	};

	changeMode(mode) {
		this.mode = mode;

		// 清理之前的事件监听器
		this._clearEventListeners();

		// 如果从画线模式切换到其他模式，清理临时线段
		if (this.lineDrawingState.isDrawing && mode !== EDITOR_STATE.DRAW_LINE) {
			this._clearTempLine();
		}

		if (mode === EDITOR_STATE.PREVIEW) {
			this._registerPreviewModeClickEvent();
		} else if (mode === EDITOR_STATE.DRAW_POINT) {
			this._registerDrawPointModeClickEvent();
		} else if (mode === EDITOR_STATE.DRAW_LINE) {
			this._registerDrawLineModeClickEvent();
		} else if (mode === EDITOR_STATE.DRAW_POLYGON) {
			this._registerDrawPolygonModeClickEvent();
		}
	}

	_clearEventListeners() {
		if (this.echartsInstance) {
			this.echartsInstance.getZr().off('click');
			this.echartsInstance.getZr().off('dblclick');
			this.echartsInstance.getZr().off('mousemove');
			this.echartsInstance.getZr().off('contextmenu');
		}
	}

	dispose() {
		this._clearEventListeners();
		if (this.echartsInstance) {
			this.echartsInstance.dispose();
		}
	}

	_registerDrawPointModeClickEvent() {
		this.echartsInstance.getZr().off('click');
		this.echartsInstance.getZr().off('dblclick');
		this.echartsInstance.getZr().off('contextmenu');

		// 初始化新增点位系列
		if (!this.eChartsOption.series[3]) {
			this.eChartsOption.series[3] = {
				type: 'scatter',
				coordinateSystem: 'cartesian2d',
				data: [],
				symbolSize: 12,
				itemStyle: {
					color: '#FF4757',
					borderColor: '#2f3542',
					borderWidth: 2
				},
				label: {
					show: true,
					position: 'top',
					color: '#2f3542',
					fontSize: 12,
					fontWeight: 'bold',
					backgroundColor: 'rgba(255, 255, 255, 0.8)',
					padding: [2, 4],
					formatter: function (params) {
						const [x, y] = params.value;
						return `(${x}, ${y})`;
					}
				},
				z: 100
			};
		}

		// 立即应用系列
		this.echartsInstance.setOption(this.eChartsOption);

		// 点击事件 - 画点
		let lastClickTime = 0;
		this.echartsInstance.getZr().on('click', params => {
			if (!params.event) return;

			// 防抖处理，避免重复点击
			const now = Date.now();
			if (now - lastClickTime < 16) return; // 100ms防抖
			lastClickTime = now;

			// 获取点击坐标
			const [px, py] = [params.offsetX, params.offsetY];
			const dataPoint = this.echartsInstance.convertFromPixel({ seriesIndex: 0 }, [px, py]);

			// 保留两位小数
			const x = Number(dataPoint[0].toFixed(2));
			const y = Number(dataPoint[1].toFixed(2));

			// 添加新点位到散点图系列
			this.eChartsOption.series[3].data.push([x, y]);
			this.echartsInstance.setOption(this.eChartsOption);

			console.log('新增点位已添加，当前数量:', this.eChartsOption.series[3].data.length);
			console.log('新增点位坐标:', { x, y });

			// 触发事件，通知外部新增了点位
			this.emit('point-added', { x, y });
		});

		// 双击删除功能
		this.echartsInstance.getZr().on('dblclick', () => {
			if (this.eChartsOption.series[3] && this.eChartsOption.series[3].data.length > 0) {
				this.eChartsOption.series[3].data.pop();
				this.echartsInstance.setOption(this.eChartsOption);
			}
		});

		// 右键退出编辑模式
		this.echartsInstance.getZr().on('contextmenu', (params) => {
			params.event.preventDefault(); // 阻止默认右键菜单
			// this.changeMode(EDITOR_STATE.PREVIEW);
			// this.emit('mode-changed', EDITOR_STATE.PREVIEW);
			this.emit('contextmenu', this.mode)
		});

		// 散点图系列会自动跟随缩放，不需要额外处理
	}

	_registerDrawLineModeClickEvent() {
		this.echartsInstance.getZr().off('click');
		this.echartsInstance.getZr().off('dblclick');
		this.echartsInstance.getZr().off('mousemove');
		this.echartsInstance.getZr().off('contextmenu');

		// 初始化画线系列 - 使用 lines 类型专门绘制线段
		if (!this.eChartsOption.series[4]) {
			this.eChartsOption.series[4] = {
				type: 'lines',
				coordinateSystem: 'cartesian2d',
				data: [],
				lineStyle: {
					color: '#FF4757',
					width: 3,
					type: 'solid',
					opacity: 0.8
				},
				z: 100,
				animation: false
			};
		}

		// 初始化画线点位系列
		if (!this.eChartsOption.series[5]) {
			this.eChartsOption.series[5] = {
				type: 'scatter',
				coordinateSystem: 'cartesian2d',
				data: [],
				symbolSize: 10,
				itemStyle: {
					color: '#FF4757',
					borderColor: '#2f3542',
					borderWidth: 2
				},
				label: {
					show: true,
					position: 'top',
					color: '#2f3542',
					fontSize: 12,
					fontWeight: 'bold',
					backgroundColor: 'rgba(255, 255, 255, 0.8)',
					padding: [2, 4],
					formatter: function (params) {
						const [x, y] = params.value;
						return `(${x}, ${y})`;
					}
				},
				z: 100
			};
		}

		// 初始化临时线段系列 - 使用 lines 类型
		if (!this.eChartsOption.series[6]) {
			this.eChartsOption.series[6] = {
				type: 'lines',
				coordinateSystem: 'cartesian2d',
				data: [],
				lineStyle: {
					color: '#FF4757',
					width: 3,
					type: 'dashed',
					opacity: 0.6
				},
				z: 99,
				animation: false
			};
			console.log('临时线段系列已初始化');
		}

		// 立即应用所有系列
		this.echartsInstance.setOption(this.eChartsOption);
		console.log('画线模式初始化完成，系列数量:', this.eChartsOption.series.length);
		console.log('系列配置:', {
			series4: this.eChartsOption.series[4],
			series6: this.eChartsOption.series[6]
		});



		// 点击事件 - 画线
		let lastLineClickTime = 0;
		this.echartsInstance.getZr().on('click', params => {
			if (!params.event) return;

			// 防抖处理，避免重复点击
			const now = Date.now();
			if (now - lastLineClickTime < 16) return; // 100ms防抖
			lastLineClickTime = now;

			// 获取点击坐标
			const [px, py] = [params.offsetX, params.offsetY];
			const dataPoint = this.echartsInstance.convertFromPixel({ seriesIndex: 0 }, [px, py]);

			// 保留两位小数
			const x = Number(dataPoint[0].toFixed(2));
			const y = Number(dataPoint[1].toFixed(2));

			if (!this.lineDrawingState.isDrawing) {
				// 第一次点击 - 开始画线
				this.lineDrawingState.isDrawing = true;
				this.lineDrawingState.startPoint = [x, y];

				// 添加起始点
				this.eChartsOption.series[5].data.push([x, y]);
				this.echartsInstance.setOption(this.eChartsOption);

				console.log('开始画线，起始点:', { x, y });
			} else {
				// 第二次点击 - 完成画线
				const endPoint = [x, y];

				// 添加结束点
				this.eChartsOption.series[5].data.push([x, y]);

				// 创建线段数据 - lines系列需要 coords 格式
				const lineData = {
					coords: [this.lineDrawingState.startPoint, endPoint]
				};

				// 添加线段到画线系列
				this.eChartsOption.series[4].data.push(lineData);
				console.log('添加最终线段:', lineData);
				console.log('当前所有线段:', this.eChartsOption.series[4].data);

				// 保存线段
				this.lineDrawingState.lines.push({
					start: this.lineDrawingState.startPoint,
					end: endPoint
				});

				this.echartsInstance.setOption(this.eChartsOption);

				console.log('完成画线，线段:', {
					start: this.lineDrawingState.startPoint,
					end: endPoint
				});

				// 清理临时线段
				if (this.eChartsOption.series[6]) {
					this.eChartsOption.series[6].data = [];
				}

				// 重置状态，准备画下一条线
				this.lineDrawingState.isDrawing = false;
				this.lineDrawingState.startPoint = null;

				// 确保更新图表
				this.echartsInstance.setOption(this.eChartsOption);
			}
		});

		// 鼠标移动事件 - 显示临时线段
		let lastUpdateTime = 0;
		this.echartsInstance.getZr().on('mousemove', params => {
			if (!this.lineDrawingState.isDrawing) return;

			// 节流处理，避免过于频繁的更新
			const now = Date.now();
			if (now - lastUpdateTime < 16) return; // 约60fps
			lastUpdateTime = now;

			const [px, py] = [params.offsetX, params.offsetY];
			const dataPoint = this.echartsInstance.convertFromPixel({ seriesIndex: 0 }, [px, py]);

			const x = Number(dataPoint[0].toFixed(2));
			const y = Number(dataPoint[1].toFixed(2));

			// 更新临时线段 - lines系列需要 coords 格式
			const tempLineData = {
				coords: [this.lineDrawingState.startPoint, [x, y]]
			};

			// 更新临时线段数据
			this.eChartsOption.series[6].data = [tempLineData];
			this.echartsInstance.setOption(this.eChartsOption);
			console.log('临时线段更新:', tempLineData, '系列数据:', this.eChartsOption.series[6].data);
			console.log('临时线段系列配置:', this.eChartsOption.series[6]);
		});

		// 双击删除功能 - 删除最后一条线段
		this.echartsInstance.getZr().on('dblclick', () => {
			if (this.lineDrawingState.lines.length > 0) {
				// 删除最后一条线段
				this.lineDrawingState.lines.pop();
				this.eChartsOption.series[4].data.pop();

				// 删除对应的两个点
				if (this.eChartsOption.series[5].data.length >= 2) {
					this.eChartsOption.series[5].data.splice(-2, 2);
				}

				this.echartsInstance.setOption(this.eChartsOption);
				console.log('删除最后一条线段');
			}
		});

		// 右键退出编辑模式
		this.echartsInstance.getZr().on('contextmenu', (params) => {
			params.event.preventDefault(); // 阻止默认右键菜单
			// 如果正在画线，清理临时线段
			if (this.lineDrawingState.isDrawing) {
				this._clearTempLine();
			}
			// this.changeMode(EDITOR_STATE.PREVIEW);
			// this.emit('mode-changed', EDITOR_STATE.PREVIEW);

			this.emit('contextmenu', this.mode)
		});
	}

	_registerDrawPolygonModeClickEvent() {
		this.echartsInstance.getZr().off('click');
		this.echartsInstance.getZr().off('dblclick');
		this.echartsInstance.getZr().off('mousemove');
		this.echartsInstance.getZr().off('contextmenu');

		// 初始化矩形系列 - 使用 lines 类型绘制矩形边框
		if (!this.eChartsOption.series[7]) {
			this.eChartsOption.series[7] = {
				type: 'lines',
				coordinateSystem: 'cartesian2d',
				data: [],
				lineStyle: {
					color: '#FF4757',
					width: 2,
					type: 'solid',
					opacity: 0.8
				},
				z: 100,
				animation: false
			};
		}

		// 初始化矩形顶点系列 - 使用 scatter 类型绘制顶点
		if (!this.eChartsOption.series[8]) {
			this.eChartsOption.series[8] = {
				type: 'scatter',
				coordinateSystem: 'cartesian2d',
				data: [],
				symbolSize: 8,
				itemStyle: {
					color: '#FF4757',
					borderColor: '#2f3542',
					borderWidth: 2
				},
				label: {
					show: true,
					position: 'top',
					color: '#2f3542',
					fontSize: 10,
					fontWeight: 'bold',
					backgroundColor: 'rgba(255, 255, 255, 0.8)',
					padding: [2, 4],
					formatter: function (params) {
						const [x, y] = params.value;
						return `(${x}, ${y})`;
					}
				},
				z: 100,
				animation: false
			};
		}

		// 初始化矩形填充系列 - 使用 scatter 类型绘制填充点
		if (!this.eChartsOption.series[10]) {
			this.eChartsOption.series[10] = {
				type: 'scatter',
				coordinateSystem: 'cartesian2d',
				data: [],
				symbolSize: 1,
				itemStyle: {
					color: '#FF4757',
					opacity: 0.1
				},
				z: 98,
				animation: false
			};
		}

		// 初始化临时矩形系列
		if (!this.eChartsOption.series[9]) {
			this.eChartsOption.series[9] = {
				type: 'lines',
				coordinateSystem: 'cartesian2d',
				data: [],
				lineStyle: {
					color: '#FF4757',
					width: 2,
					type: 'dashed',
					opacity: 0.6
				},
				z: 99,
				animation: false
			};
		}

		// 初始化临时矩形顶点系列
		if (!this.eChartsOption.series[11]) {
			this.eChartsOption.series[11] = {
				type: 'scatter',
				coordinateSystem: 'cartesian2d',
				data: [],
				symbolSize: 6,
				itemStyle: {
					color: '#FF4757',
					borderColor: '#2f3542',
					borderWidth: 1
				},
				label: {
					show: true,
					position: 'top',
					color: '#2f3542',
					fontSize: 9,
					fontWeight: 'bold',
					backgroundColor: 'rgba(255, 255, 255, 0.8)',
					padding: [1, 3],
					formatter: function (params) {
						const [x, y] = params.value;
						return `(${x}, ${y})`;
					}
				},
				z: 99,
				animation: false
			};
		}

		// 立即应用所有系列
		this.echartsInstance.setOption(this.eChartsOption);
		console.log('画矩形模式初始化完成');

		// 矩形绘制状态
		let isDrawingRectangle = false;
		let startPoint = null;

		// 点击事件 - 画矩形
		let lastClickTime = 0;
		this.echartsInstance.getZr().on('click', params => {
			if (!params.event) return;

			// 防抖处理
			const now = Date.now();
			if (now - lastClickTime < 16) return;
			lastClickTime = now;

			// 获取点击坐标
			const [px, py] = [params.offsetX, params.offsetY];
			const dataPoint = this.echartsInstance.convertFromPixel({ seriesIndex: 0 }, [px, py]);
			const x = Number(dataPoint[0].toFixed(2));
			const y = Number(dataPoint[1].toFixed(2));

			if (!isDrawingRectangle) {
				// 第一次点击 - 开始画矩形
				isDrawingRectangle = true;
				startPoint = [x, y];
				console.log('开始画矩形，起始点:', { x, y });
			} else {
				// 第二次点击 - 完成画矩形
				const endPoint = [x, y];

				// 计算矩形的四个顶点
				const rectPoints = this._calculateRectanglePoints(startPoint, endPoint);

				// 创建矩形边框线段数据
				const rectLines = this._createRectangleLines(rectPoints);

				// 添加矩形边框到系列
				this.eChartsOption.series[7].data.push(...rectLines);

				// 添加矩形顶点到系列
				this.eChartsOption.series[8].data.push(...rectPoints);

				// 创建矩形填充数据
				const fillPoints = this._createRectangleFillPoints(rectPoints);
				this.eChartsOption.series[10].data.push(...fillPoints);

				this.echartsInstance.setOption(this.eChartsOption);

				console.log('完成画矩形:', {
					start: startPoint,
					end: endPoint,
					points: rectPoints
				});

				// 清理临时矩形
				this.eChartsOption.series[9].data = [];
				this.eChartsOption.series[11].data = [];

				// 重置状态
				isDrawingRectangle = false;
				startPoint = null;

				this.echartsInstance.setOption(this.eChartsOption);
			}
		});

		// 鼠标移动事件 - 显示临时矩形
		let lastUpdateTime = 0;
		this.echartsInstance.getZr().on('mousemove', params => {
			if (!isDrawingRectangle) return;

			// 节流处理
			const now = Date.now();
			if (now - lastUpdateTime < 16) return;
			lastUpdateTime = now;

			const [px, py] = [params.offsetX, params.offsetY];
			const dataPoint = this.echartsInstance.convertFromPixel({ seriesIndex: 0 }, [px, py]);
			const x = Number(dataPoint[0].toFixed(2));
			const y = Number(dataPoint[1].toFixed(2));

			// 计算临时矩形的四个顶点
			const tempRectPoints = this._calculateRectanglePoints(startPoint, [x, y]);

			// 创建临时矩形边框线段数据
			const tempRectLines = this._createRectangleLines(tempRectPoints);

			// 更新临时矩形数据
			this.eChartsOption.series[9].data = tempRectLines;
			// 更新临时矩形顶点数据
			this.eChartsOption.series[11].data = tempRectPoints;
			this.echartsInstance.setOption(this.eChartsOption);
		});

		// 双击删除功能 - 删除最后一个矩形
		this.echartsInstance.getZr().on('dblclick', () => {
			// 删除最后一个矩形的边框（4条线段）
			if (this.eChartsOption.series[7].data.length >= 4) {
				this.eChartsOption.series[7].data.splice(-4, 4);
			}

			// 删除最后一个矩形的顶点（4个点）
			if (this.eChartsOption.series[8].data.length >= 4) {
				this.eChartsOption.series[8].data.splice(-4, 4);
			}

			// 删除最后一个矩形的填充点
			if (this.eChartsOption.series[10].data.length > 0) {
				// 删除填充点（这里简化处理，删除最后一批点）
				this.eChartsOption.series[10].data.splice(-100, 100);
			}

			this.echartsInstance.setOption(this.eChartsOption);
			console.log('删除最后一个矩形');
		});

		// 右键退出编辑模式
		this.echartsInstance.getZr().on('contextmenu', (params) => {
			params.event.preventDefault(); // 阻止默认右键菜单
			// 如果正在画矩形，清理临时矩形
			if (isDrawingRectangle) {
				this.eChartsOption.series[9].data = [];
				this.eChartsOption.series[11].data = [];
				this.echartsInstance.setOption(this.eChartsOption);
			}
			// this.changeMode(EDITOR_STATE.PREVIEW);
			// this.emit('mode-changed', EDITOR_STATE.PREVIEW);

			this.emit('contextmenu', this.mode)
		});
	}

	// 计算矩形的四个顶点
	_calculateRectanglePoints(startPoint, endPoint) {
		const [x1, y1] = startPoint;
		const [x2, y2] = endPoint;

		// 计算矩形的四个顶点（按顺时针顺序）
		const points = [
			[x1, y1], // 左上角
			[x2, y1], // 右上角
			[x2, y2], // 右下角
			[x1, y2]  // 左下角
		];

		return points;
	}

	// 创建矩形边框线段数据
	_createRectangleLines(points) {
		const lines = [];

		// 创建4条边
		for (let i = 0; i < 4; i++) {
			const currentPoint = points[i];
			const nextPoint = points[(i + 1) % 4];

			lines.push({
				coords: [currentPoint, nextPoint]
			});
		}

		return lines;
	}

	// 创建矩形填充点数据
	_createRectangleFillPoints(points) {
		const [x1, y1] = points[0];
		const [x2, y2] = points[2];

		const fillPoints = [];
		const step = 1; // 填充点的间距，增大以减少点的数量

		// 在矩形区域内生成填充点
		const minX = Math.min(x1, x2);
		const maxX = Math.max(x1, x2);
		const minY = Math.min(y1, y2);
		const maxY = Math.max(y1, y2);

		// 限制填充点的数量，避免性能问题
		const maxPoints = 1000;
		let pointCount = 0;

		for (let x = minX; x <= maxX && pointCount < maxPoints; x += step) {
			for (let y = minY; y <= maxY && pointCount < maxPoints; y += step) {
				fillPoints.push([x, y]);
				pointCount++;
			}
		}

		return fillPoints;
	}

	_registerPreviewModeClickEvent() {
		this.echartsInstance.getZr().off('click');

		this.echartsInstance.getZr().on('click', (params) => {
			this.emit('click', {
				...params,
				mode: this.mode
			});
		});
	}
};

export default EchartsController;